package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.vo.PageResult;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entity.TbBrand;
import com.leyou.item.entity.TbCategoryBrand;
import com.leyou.item.mapper.TbBrandMapper;
import com.leyou.item.service.TbBrandService;
import com.leyou.item.service.TbCategoryBrandService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 品牌表，一个品牌下有多个商品（spu），一对多关系 服务实现类
 * </p>
 *
 * @author HM
 * @since 2020-10-07
 */
@Service
public class TbBrandServiceImpl extends ServiceImpl<TbBrandMapper, TbBrand> implements TbBrandService {

    /**
     * 分页查询品牌信息
     * @param key
     * @param page
     * @param rows
     * @param sortBy
     * @param desc
     * @return
     */
    @Override
    public PageResult<BrandDTO> findBrandByPage(String key, Integer page, Integer rows, String sortBy, Boolean desc) {
//        select * from tb_brand where name like '%?%' order by ? desc/asc  limit ?,?
//        构造分页条件
        Page<TbBrand> page1 = new Page<>(page,rows);
//        构造查询条件
        QueryWrapper<TbBrand> queryWrapper = new QueryWrapper<>();
        if(!StringUtils.isBlank(key)){
//          如果key不为空，需要sql添加key的条件
            queryWrapper.lambda().like(TbBrand::getName,key);
        }
        if(!StringUtils.isBlank(sortBy)){
//          如果sortby不为空，就设置排序
            if(desc){
                queryWrapper.orderByDesc(sortBy);
            }else{
                queryWrapper.orderByAsc(sortBy);
            }

        }
//        查询分页结果
        IPage<TbBrand> brandIPage = page(page1,queryWrapper);

        if(brandIPage == null || CollectionUtils.isEmpty(brandIPage.getRecords())){
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        List<BrandDTO> brandDTOList = BeanHelper.copyWithCollection(brandIPage.getRecords(), BrandDTO.class);
        return new PageResult<BrandDTO>(brandDTOList,brandIPage.getPages(),brandIPage.getTotal());
    }

    @Autowired
    private TbCategoryBrandService tbCategoryBrandService;
    /**
     * 保存品牌 需要包含事务
     * 保存2张表
     * tb_brand  tb_category_brand
     * @param tbBrand
     * @param cids
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)//开启事务
    public void saveBrand(TbBrand tbBrand, List<Long> cids) {

//        保存品牌表
        boolean b = save(tbBrand);
        if(!b){
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
        Long brandId = tbBrand.getId();
//        保存中间表,需要brandid，需要cid
        List<TbCategoryBrand> tbCategoryBrandList = new ArrayList<>();
        for (Long cid : cids) {
            TbCategoryBrand tbCategoryBrand = new TbCategoryBrand();
            tbCategoryBrand.setBrandId(brandId);
            tbCategoryBrand.setCategoryId(cid);
            tbCategoryBrandList.add(tbCategoryBrand);
        }
        if(CollectionUtils.isEmpty(tbCategoryBrandList)){
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
        boolean b1 = tbCategoryBrandService.saveBatch(tbCategoryBrandList);
        if(!b1){
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
    }

    /**
     * 修改品牌信息
     * 操作2张表
     * @param tbBrand
     * @param cids
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateBrand(TbBrand tbBrand, List<Long> cids) {

        Long brandId = tbBrand.getId();
        boolean b = updateById(tbBrand);
        if(!b){
           throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }
//        delete from tb_category_brand where brand_id=?
//        构造条件
        QueryWrapper<TbCategoryBrand> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TbCategoryBrand::getBrandId,brandId);
//        操作中间表，先删除内容，再新增内容
        boolean b1 = tbCategoryBrandService.remove(queryWrapper);
        if(!b1){
            throw new LyException(ExceptionEnum.DELETE_OPERATION_FAIL);
        }
//        把新的数据写入中间表
        //        保存中间表,需要brandid，需要cid
        List<TbCategoryBrand> tbCategoryBrandList = new ArrayList<>();
        for (Long cid : cids) {
            TbCategoryBrand tbCategoryBrand = new TbCategoryBrand();
            tbCategoryBrand.setBrandId(brandId);
            tbCategoryBrand.setCategoryId(cid);
            tbCategoryBrandList.add(tbCategoryBrand);
        }
        if(CollectionUtils.isEmpty(tbCategoryBrandList)){
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
        boolean b2 = tbCategoryBrandService.saveBatch(tbCategoryBrandList);
        if(!b2){
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
    }

    /**
     * 根据分类id查询品牌集合
     * @param cid
     * @return
     */
    @Override
    public List<BrandDTO> findBrandListByCid(Long cid) {
//        SELECT a.* FROM tb_brand a,tb_category_brand b WHERE b.`category_id`=76 AND a.id = b.`brand_id`
        List<TbBrand> tbBrandList = getBaseMapper().selectBrandByCid(cid);
        if(CollectionUtils.isEmpty(tbBrandList)){
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(tbBrandList,BrandDTO.class);
    }
}
